//
//  MaskingView.m
//  iHomeDesign
//
//  Created by WC on 2020/3/29.
//  Copyright © 2021年 YH. All rights reserved.
//

#import "MaskingView.h"

typedef void(^TouchCompletedBlock)(void);

@interface MaskingView ()

@property (nonatomic, strong)UIView *contentView;
@property (nonatomic, assign)BOOL RemoveByBgView;//点击背景是否能收起来
@end

@implementation MaskingView

- (instancetype)initWithContentView:(UIView *)contentView RemoveByBgView:(BOOL)RemoveByBgView
{
    self = [super initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    if (self = [super init]) {
        self.contentView = contentView;
        self.RemoveByBgView = RemoveByBgView;
        [self layoutAllSubviews];
    }
    return self;
}

- (instancetype)initWithContentView:(UIView *)contentView{

    return [self initWithContentView:contentView RemoveByBgView:YES];
}

- (void)layoutAllSubviews{
    UIWindow * window = [[[UIApplication sharedApplication] delegate] window];
    
    for (UIView *view in window.subviews) {
        if ([view isKindOfClass:[self class]]) {
            MaskingView *V = (MaskingView*)view;
            //浏览图片不移除
            if (![V.contentView isKindOfClass:NSClassFromString(@"YHCircleCollectionView")]) {
                [V.contentView removeFromSuperview];
                [V removeFromSuperview];
            }
        }
    }
    
    [window addSubview:self];
    
    UIView *bgView = [[UIView alloc] initWithFrame:self.frame];
    [self addSubview:bgView];
    self.bgView = bgView;
    bgView.alpha = 0.8;
    bgView.backgroundColor = HHColorHex000000;

    [self addSubview:self.contentView];
    
    self.alpha = 0;
    __weak typeof(self)weakSelf = self;
    [UIView animateWithDuration:0.5 animations:^{
        weakSelf.alpha = 1;
    }];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissContactView:)];
 
    if (self.RemoveByBgView) {
      [bgView addGestureRecognizer:tapGesture];
    }
    
}
#pragma mark - 手势点击事件,移除View
- (void)dismissContactView:(UITapGestureRecognizer *)tapGesture{
    
    if (self.RemoveBlock) {
        self.RemoveBlock();
    }
    
    __weak typeof(self)weakSelf = self;
    [UIView animateWithDuration:0.5 animations:^{
        weakSelf.alpha = 0;
    } completion:^(BOOL finished) {
        [weakSelf.contentView removeFromSuperview];
        [weakSelf removeFromSuperview];
    }];
}


@end


